package cn.zf233.springsecurityjwt.config.handler;

import cn.zf233.springsecurityjwt.common.R;
import cn.zf233.springsecurityjwt.entity.User;
import cn.zf233.springsecurityjwt.util.JwtUtil;
import cn.zf233.springsecurityjwt.util.ServletUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by zf233 on 2021/7/12
 */
@Component
public class MySuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        //登录的用户信息验证成功后执行的方法
        Long id = ((User) authentication.getPrincipal()).getId();
        String token = jwtUtil.createTokenByUserId(id, TimeUnit.DAYS.toMillis(7L));
        ServletUtil.renderString(response, R.createBySuccess("登陆成功", token));
    }
}
